<template>
  <div class="detailCon">
    <div class="row detailItem items-center justify-between" v-if="useWODetails.displayConfig.show_Production_Notes">
      <div class="col-auto"><span class="dTitle">生产备注</span></div>
      <div v-if="role === 'DISPATCHER'" class="col-auto">
        <div v-if="!editModeProdRemark">
          <q-btn
            color="deep-purple-4"
            class="editBtn col"
            label="编辑"
            @click="editModeProdRemark = true"
          >
            <q-icon name="fa-solid fa-pen" class="editSVG" />
          </q-btn>
        </div>
        <div v-else>
          <q-btn
            color="grey-8"
            class="cancelBtn"
            label="取消"
            @click="cancelProdRemark()"
          >
          </q-btn>
          <q-btn
            color="deep-purple-4"
            class="saveBtn"
            label="储存"
            @click="saveProdRemark()"
          >
            <q-icon name="fa-solid fa-floppy-disk" class="saveSVG" />
          </q-btn>
        </div>
      </div>
    </div>
    <div class="row detailItem" v-if="useWODetails.displayConfig.show_Production_Notes">
      <table class="remarkTable">
        <thead>
          <tr>
            <th>镶石备注内容分类</th>
            <th width="100" v-if="editModeProdRemark"></th>
            <th v-if="editModeProdRemark"></th>
          </tr>
        </thead>
        <!-- Readonly prod remark -->
        <tbody v-if="!editModeProdRemark">
          <tr v-for="epr in curProdRemark" :key="epr.pk">
            <td v-if="epr.type === 'INT' && epr.ans > 0">
              <span v-if="epr.remark.length > 1"
                >{{ epr.remark[0] }} {{ epr.ans }} {{ epr.remark[1] }}</span
              >
              <span v-else>{{ epr.remark[0] }} {{ epr.ans }}</span>
            </td>
            <td v-else-if="epr.ans > 0">
              {{ epr.remark[0] }}
            </td>
          </tr>
        </tbody>

        <tbody v-else>
          <tr
            v-for="(epr, index) in editProdRemark"
            :key="epr.pk"
            :class="{ isChosen: epr.isChosen }"
          >
            <td v-if="epr.type === 'INT'">
              <span v-if="epr.remark.length > 1"
                >{{ epr.remark.replace('<NUM>',epr.ans != undefined ? epr.ans: '_') }}</span
              >
              <span v-else>{{ epr.remark }} {{ epr.ans }}</span>
            </td>
            <td v-else>
              {{ epr.remark }}
            </td>

            <td v-if="epr.type === 'INT'" class="editProdInput">
              <q-input
                densed
                v-model.number="epr.ans"
                type="number"
                bg-color="white"
                filled
                outlined
                dense
                placeholder="输入..."
              />
            </td>
            <td v-else></td>

            <td>
              <q-icon
                v-if="!epr.isChosen"
                name="fa-solid fa-circle-plus"
                class="addSVG"
                @click="toggleProdRemark('add', epr.pk, index)"
              />
              <q-icon
                v-else
                name="fa-solid fa-circle-minus"
                class="removeSVG"
                @click="toggleProdRemark('remove', epr.pk, index)"
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <q-separator />

    <div v-if="showsiTable&&useWODetails.displayConfig.show_Ingredients" class="row detailItem">
      <div class="col-auto"><span class="dTitle">原料清单</span></div>
      <q-table
        flat
        bordered
        dense
        separator="cell"
        table-header-class="bg-indigo-2"
        :rows="sirows"
        :columns="sicolumns"
        row-key="seqNo"
        class="rawMatTable"
        :pagination="{ rowsPerPage: 10 }"

      />
    </div>
    <q-separator />

    <div v-if="stoneIssue !== undefined&&useWODetails.displayConfig.show_Stone_Issue" class="row detailItem">
      <span class="col dTitle">石问题</span>
      <span class="col dValue">{{ stoneIssue }}</span>
    </div>
    <q-separator />

    <div v-if="showAb&&useWODetails.displayConfig.show_Stone_Detail" class="row detailItem">
      <span class="col-auto dTitle">发石明细资料</span>
      <span class="col dValue"
        >总粒数: {{ totalQty }}粒 总CT数: {{ totalCTCnt }} 总计:
        {{ totalWeight }}g</span
        >
        <q-btn icon="refresh" color="deep-purple-8" size="sm" @click="refreshActualBom"></q-btn>
    </div>
    <div v-if="showAb&&useWODetails.displayConfig.show_Stone_Detail" class="row detailItem">
      <div class="tableBox">
        <q-table
          flat
          bordered
          dense
          separator="cell"
          table-header-class="bg-deep-purple-2"
          :rows="bomrows"
          :columns="bomcolumns"
          row-key="seqNo"
          class="bomTable"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useUserStore } from "src/stores/modules/userStore";
import { useWoDetailsStore } from "src/stores/modules/wodetailsStore";

// Check User Role
const userStore = useUserStore();
let role = null;
let showProdRemark = ref(false);
let showAb = ref(false);
let showsiTable = ref(false);




if (userStore.currentDept != null) {
  role = userStore.currentDept.roleGroup;
  console.log("role: ", role);
}

// All data values
let si = null;
let stoneIssue = null;
let ab = null;
let pr = null;
const totalCTCnt = ref(0);
const totalQty = ref(0);
const totalWeight = ref(0);

// Get values
const useWODetails = useWoDetailsStore();

// Production Remark [EDIT MODE]
const editModeProdRemark = ref(false);

const editProdRemark = ref([]);
const curProdRemark = ref([]);

const init = () => {
  si = useWODetails.prodInfo.stoneInfo;
  stoneIssue = useWODetails.prodInfo.stoneIssue;
  ab = useWODetails.prodInfo.actualBom;
  pr = useWODetails.new_productionRemark;
  showProdRemark.value = pr !== undefined;
  showsiTable.value = si !== undefined;
  showAb.value = ab !== undefined;

  totalCTCnt.value = ab.totalCTCnt;
  totalQty.value = ab.totalQty;
  totalWeight.value = ab.totalWeight;
  console.log("useWODetails.prodInfo.stoneInfo", si);
};
editProdRemark.value = [
  ...JSON.parse(JSON.stringify(useWODetails.new_productionRemark)),
];
curProdRemark.value = [
...useWODetails.currProdRemark
]

console.log("editProdRemark: ", editProdRemark.value);
console.log("curProdRemark: ", curProdRemark.value);
init();

// Stone Info table
let sicolumns = [];
let sirows = [];

sicolumns = [
  {
    name: "article",
    required: true,
    label: "原料编号",
    align: "center",
    field: (row) => row.article,
    format: (val) => `${val}`,
    sortable: false,
  },
  {
    name: "article_description",
    align: "center",
    label: "原料描述",
    field: "article_description",
    sortable: false,
  },
  {
    name: "quantity",
    align: "center",
    label: "数量",
    field: "qty",
    sortable: false,
  },
  {
    name: "weight",
    align: "center",
    label: "重量",
    field: "weight",
    sortable: false,
  },
];

sirows = si;

// Actual BOM table
let bomcolumns = [];
let bomrows = ref([]);

bomcolumns = [
  {
    name: "seq",
    required: true,
    label: "件数序号",
    align: "center",
    field: (row) => row.seq,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "laser_mark",
    align: "center",
    label: "镭射字印",
    field: "laser_mark",
    sortable: false,
  },
  {
    name: "article",
    align: "center",
    label: "货品名称",
    field: "article",
    sortable: false,
  },
  {
    name: "is_main_stone",
    align: "center",
    label: "是否主石",
    field: "is_main_stone",
    sortable: false,
  },
  {
    name: "stone_cert",
    align: "center",
    label: "证书编号",
    field: "stone_cert",
    sortable: false,
  },
  {
    name: "stone_color",
    align: "center",
    label: "颜色",
    field: "stone_color",
    sortable: false,
  },
  {
    name: "stone_clarity",
    align: "center",
    label: "净度",
    field: "stone_clarity",
    sortable: false,
  },
  {
    name: "weight",
    align: "center",
    label: "重量",
    field: "weight",
    sortable: false,
  },
  {
    name: "unit",
    align: "center",
    label: "单位",
    field: "unit",
    sortable: false,
  },
  {
    name: "quantity",
    align: "center",
    label: "粒数",
    field: "quantity",
    sortable: false,
  },
];

bomrows.value = ab.stoneInfo;
bomrows.value.forEach((e) => {
  e.is_main_stone = e.is_main_stone ? "是" : "否";
});

const toggleProdRemark = (act, pk, index) => {
  console.log("act: ", act, "pk: ", pk, "index: ", index);
  const target = editProdRemark.value[index];
  // console.log('target: ', target)
  if (target) {
    editProdRemark.value[index].isChosen = act === "add" ? true : false;
  } else {
    console.log("cannot find index");
  }
  console.log("updated value: ", editProdRemark.value[index]);
};

const cancelProdRemark = () => {
  console.log("cancel Changes");
  if (editProdRemark.value.length > 0) {
    editProdRemark.value.forEach((e) => {
      e.ans = e.prev_ans;
      e.isChosen = e.ans > 0 ? true : false;
    });
    console.log("reset changes: ", editProdRemark.value);
  }
  editModeProdRemark.value = false;
};

const saveProdRemark = async () => {
  console.log("save prodremark");
  if (editProdRemark.value.length > 0) {
    editProdRemark.value.forEach((e) => {
      e.ans = e.isChosen ? (e.type === "BOOL" ? 1 : e.ans) : 0;
      e.isChosen = e.ans > 0 ? true : false;
    });
    console.log("save changes: ", editProdRemark.value);
  }
  // call api
  const res = await useWODetails.updateProdRemark(editProdRemark.value);
  if (res) {
    editModeProdRemark.value = false;
    console.log(curProdRemark.value);
    console.log(editProdRemark.value);
    const newArr = editProdRemark.value.map((i)=>{
      if (i.type=='INT'){
        return {
          ...i,
          remark: i.remark.split('<NUM>')
        }
      }
      return {
        ...i,
        remark: [i.remark]
      }
    })
    curProdRemark.value = [...newArr]
    // curProdRemark.value.forEach((e) => {
    //   console.log(e);
    //   e.prev_ans = e.ans;
    // });
  } else {
    //error
    curProdRemark.value.forEach((e) => {
      e.ans = e.prev_ans;
      e.isChosen = e.ans > 0 ? true : false;
    });
  }
};

async function refreshActualBom() {
  const res = await useWODetails.getActualBom()
  if (res){
    showAb.value = true
    bomrows.value = res.data.data.actualBom

    // bomrows.value = [
    //   { "seq": 1, "laser_mark": null, "article": "DDDDFCXXEEP000XX", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.025", "unit": "CT", "quantity": "7.00" }, 
    //   { "seq": 2, "laser_mark": null, "article": "DDDDFCXXEEP000XX", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.025", "unit": "CT", "quantity": "7.00" }, 
    //   { "seq": 3, "laser_mark": null, "article": "DDDDFCXXEEP0000X", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.124", "unit": "CT", "quantity": "48.00" }, 
    //   { "seq": 4, "laser_mark": null, "article": "DDDDFCXXEEP0000X", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.124", "unit": "CT", "quantity": "48.00" }, 
    //   { "seq": 5, "laser_mark": null, "article": "DDDDFCXXEEP000XX", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.025", "unit": "CT", "quantity": "7.00" }, 
    //   { "seq": 6, "laser_mark": null, "article": "DDDDFCXXEEP000XX", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.025", "unit": "CT", "quantity": "7.00" }, 
    //   { "seq": 7, "laser_mark": null, "article": "DDDDFCXXEEP0000X", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.124", "unit": "CT", "quantity": "48.00" },
    //   { "seq": 8, "laser_mark": null, "article": "DDDDFCXXEEP0000X", "is_main_stone": false, "stone_cert": "", "stone_color": "", "stone_clarity": "", "weight": "0.124", "unit": "CT", "quantity": "48.00" } 
    // ]
    bomrows.value.forEach((e) => {
      e.is_main_stone = e.is_main_stone ? "是" : "否";
    });
  }
}
</script>

<style lang="scss" scoped>
.detailCon {
  background-color: rgba(255, 255, 255, 0.9);
  margin: 10px 5px 5px 5px;
  border-radius: 10px;
  padding: 10px 5px 5px 10px;
  font-size: 1.1rem;
  @media (max-width: 480px) {
    font-size: 0.7em;
    margin: 0px 5px 5px 5px;
  }
  .detailItem {
    margin-top: 5px;
    margin-bottom: 5px;
    .dTitle {
      color: black;
      font-weight: bold;
    }
    .dValue {
      margin-left: 5px;
    }

    .remarkTable {
      width: 100%;
      thead {
        width: 100%;
        text-align: center;
        background-color: #beccf9;
      }
      tbody td {
        background-color: white;
        text-align: center;
        font-weight: bold;
      }
      .noProdRemark {
        font-size: 0.7rem;
        color: #9b9b9b;
      }
    }

    .addSVG,
    .removeSVG {
      color: #9a91f2;
    }

    .isChosen {
      td {
        background-color: #a7bffe !important;
      }
      .addSVG,
      .removeSVG {
        color: white;
      }
    }

    .editSVG,
    .saveSVG {
      font-size: 1rem;
      margin-left: 5px;
    }
    .cancelBtn {
      margin-right: 5px;
    }

    .rawMatTable {
      width: 100%;
      thead {
        width: 100%;
        text-align: center;
        background-color: #96a1d6;
      }
      tbody td {
        background-color: rgb(248, 247, 247);
        text-align: center;
      }
    }

    .tableBox {
      overflow: hidden;
    }
    .bomTable {
      width: 100%;

      thead {
        width: 100%;
        text-align: center;
        background-color: #c7c3e0;
      }
      tbody td {
        background-color: white;
        text-align: center;
      }
    }
  }

  .editProdInput {
    width: 50px;
  }
}
</style>
